
package org.filetransfer.file_transfer_java_backend.service;
import org.filetransfer.file_transfer_java_backend.entity.Message;
import org.filetransfer.file_transfer_java_backend.repository.MessageRepository;
import org.filetransfer.file_transfer_java_backend.repository.ShareItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
public class MessageService {
    @Autowired
    private MessageRepository messageRepository;
    @Autowired
    private ShareItemService shareItemService;
    @Autowired
    private ShareItemRepository shareItemRepository;
    public Message addMessage(String code, String token, String message) {
        var shareItem = shareItemService.getShareItem(code)// 获取分享
                .orElseThrow(() -> new RuntimeException("分享" + code + "未找到"));
        shareItemService.verifyEditTokenOrThrow(shareItem, token);// 验证token
        var messageEntity = new Message();
        messageEntity.setShareItem(shareItem);
        messageEntity.setContent(message);
        shareItem.getMessages().add(messageEntity);
        return messageRepository.save(messageEntity);
    }    public boolean deleteMessage(String code, String token, long msgId) {
        var shareItem = shareItemService.getShareItem(code)// 获取分享
                .orElseThrow(() -> new RuntimeException("分享" + code + "未找到"));
        shareItemService.verifyEditTokenOrThrow(shareItem, token);// 验证token
        
        // 找到要删除的消息
        var messageToDelete = shareItem.getMessages().stream()
                .filter(m -> m.getId().equals(msgId))
                .findFirst();
        
        if (messageToDelete.isPresent()) {
            // 从集合中移除
            shareItem.getMessages().remove(messageToDelete.get());
            // 从数据库中删除
            messageRepository.delete(messageToDelete.get());
            // 保存ShareItem（可选，因为已经直接删除了Message）
//            shareItemRepository.save(shareItem);
            return true;
        }
        return false;
    }
    public List<Message> getMessages(String code) {
        var shareItem = shareItemService.getShareItem(code)// 获取分享
                .orElseThrow(() -> new RuntimeException("分享" + code + "未找到"));
        return shareItem.getMessages();
    }
}

